package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 预约设置服务
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    //批量导入预约设置
    public void add(List<OrderSetting> data) {
        if(data != null){
            for (OrderSetting orderSetting : data) {
                //判断当前日期是否已经进行了预约设置
                long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if(countByOrderDate > 0){
                    //证明已经进行了预约设置
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else {
                    //没有进行预约设置
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    //根据月份查询对应的预约设置数据
    public List<Map> getOrderSettingByMouth(String date) {//格式yyyy-MM
        String begin = date + "-1";//2019-6-1
        String end = date + "-31";//2019-6-31

        Map<String, String> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);

        //调用DAO，根据日期范围查询预约设置数据
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMouth(map);

        List<Map> result = new ArrayList<>();

        if(list != null && list.size() > 0){
            for (OrderSetting orderSetting : list) {
                Map<String, Object> m = new HashMap<>();
                m.put("date", orderSetting.getOrderDate().getDate());//获取预约日期
                m.put("number", orderSetting.getNumber());
                m.put("reservations", orderSetting.getReservations());//已预约人数
                result.add(m);
            }
        }

        return result;
    }

    //根据日期修改预约数量
    public void editNumberByDate(OrderSetting orderSetting) {
        //根据日期查询是否已经进行了预约设置操作
        Date orderDate = orderSetting.getOrderDate();
        long count = orderSettingDao.findCountByOrderDate(orderDate);

        if(count > 0){
            //已经预约设置过，需要进行修改
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else {
            //当前日期还没有进行预约设置，需要进行添加操作
            orderSettingDao.add(orderSetting);
        }
    }
}
